#! /bin/bash

SVN="/usr/bin/svn"

logf="/dev/null"
function log(){
  log_file="`basename $0`@`hostname`.log"
  for log_dir in /var/log "$HOME" . /tmp /dev/null
  do
    [ -w "$log_dir" ] && touch "$log_dir/$log_file" && break
  done
  log_url="$log_dir/$log_file"
  [ ! -w "$log_url" ] && return
  logf="$log_url"

  log_msg="$1"
  [ "$1" == "time" ] && log_msg="[`date +'%Y/%m/%d %H:%M:%S'`]: $2"
  echo "$log_msg" >> "$log_url"
  echo "$log_msg"
  return
}

#=========================================================================

function get_url(){
  $SVN info "$1" 2>/dev/null | awk '( $1 ~ /^URL:/){print $2}'
}

function get_rev(){
  $SVN info "$1" 2>/dev/null | awk '( $1 ~ /^Revision:/){print $2}'
}

function is_svn_repo(){
  $SVN info "$1" 1>/dev/null 2>&1
  [ $? -eq 0 ] && echo "true" && return
  echo "false" && return
}

function svn_up()
{
  dir_name="$1"
  if [ "`is_svn_repo $dir_name`" == "true" ]
  then
    last_rev="`get_rev $dir_name`"
    url="`get_url $dir_name`"
    log "[*] svn up \"$dir_name\" ($url)"
    $SVN up "$dir_name" 1>/dev/null 2>&1
    this_rev="`get_rev $dir_name`"
    [ "$last_rev" == "$this_rev" ] && log "    no changes." && return
    log "    [$last_rev] -> [$this_rev]" && return
  else
    log "--- skip \"$dir_name\" since it is not a svn repo"
  fi
  return
}


function svn_up_all()
{
  log ""
  log "time" "Update all svn dir under: $1"
  find "$1" -maxdepth 1 2>/dev/null | while read sub_dir
  do
    [ -d "$sub_dir" -a -w "$sub_dir" ] && svn_up "$sub_dir"
  done
  log ""
  return 0
}

# $* refer to the list
function svn_up_list()
{
  log ""
  log "time" "Update svn dir list: $*"
  for sub_dir in $*
  do
    [ -d "$sub_dir" -a -w "$sub_dir" ] && svn_up "$sub_dir"
  done
  log ""
}

if [ "`id -u`" != "0" ]
then
  # Normal user
  svn_up_list "$HOME/lancez"
  exit 0
fi

# the following scripts only works for user root

log "`/usr/sbin/ntpdate ntp.hp.net 2>&1`"

[ -w "/lancez" ] && svn_up_list "/lancez"
[ -w /etc ]      && svn_up_list /etc/bind/
[ -w /pbfd/manageability ]     && svn_up_all "/pbfd/manageability/"
[ -w /pbfd/manageability/smx ] && svn_up_all "/pbfd/manageability/smx/"


